package com.shatower.chatctrl.controller;

import com.alibaba.fastjson.JSON;
import com.shatower.chatctrl.dao.pojo.*;
import com.shatower.chatctrl.dao.pojo.Groups;
import com.shatower.chatctrl.dao.service.*;
import com.shatower.chatctrl.result.*;
import com.shatower.chatctrl.utils.RedisSource;
import com.shatower.chatctrl.utils.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.*;

/**
 * Created by hhggccll on 2017/10/16.
 */
@Controller
@RequestMapping("/downlink")
public class DownlinkController extends  BaseController {

    @Autowired
    private CircleService circleService;

    @Autowired
    private RedisSource redisSource;

    @Autowired
    private GroupsService groupService;

    @Autowired
    private UserService userService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private  FriendService friendService;

    private String choice(List<String> initMembers){

        //检索出管理的微信群最少的管理员
        VolunteerExample volunteerExample = new VolunteerExample();
        VolunteerExample.Criteria  criteriaV = volunteerExample.createCriteria();

        Date now = new Date();

        Calendar rightNow1 = Calendar.getInstance();
        rightNow1.setTime(now);
        //rightNow1.set(Calendar.MINUTE,rightNow1.get(Calendar.MINUTE)-4);
        rightNow1.set(Calendar.HOUR_OF_DAY,rightNow1.get(Calendar.HOUR_OF_DAY)-2);
            //聊天记录定时上传时，更新时间戳，超过4分钟没有更新，认为手机已经关闭微信了
        Date  accessTime = rightNow1.getTime();
        criteriaV.andUpdatetimeGreaterThan(accessTime);

        List<Volunteer>  volunteers =  volunteerService.selectByExample(volunteerExample);
        if(volunteers==null ||volunteers.size()==0){
            return null;
        }
        List<String> stringList = new ArrayList<>();
        for(Volunteer v: volunteers){
            stringList.add(v.getVolunteerweixinid());
        }


        GroupsExample groupExample = new GroupsExample();
        GroupsExample.Criteria criteriaGroup = groupExample.createCriteria();

        criteriaGroup.andAdminweixinidIn(stringList);
        List<Groups> groups = groupService.selectByExample(groupExample);
        HashMap<String,Integer>  integerHashMap = new HashMap<>();


        List<Map.Entry<String, Integer>> infoIds =null;
        if(groups==null ||groups.size()==0){
            integerHashMap.put(volunteers.get(0).getVolunteerweixinid(),1);
        }else {
            for (Volunteer v : volunteers) {
                integerHashMap.put(v.getVolunteerweixinid(), new Integer(0));
            }

            for (Groups group : groups) {
                Integer gg = integerHashMap.get(group.getAdminweixinid());
                if (gg == null) {
                    gg = new Integer(0);
                }
                gg += 1;
                integerHashMap.put(group.getAdminweixinid(), gg);
            }
        }

        infoIds = new ArrayList<>(integerHashMap.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {

                return o1.getValue().compareTo(o2.getValue());
            }
        });

        //随机获得管理员的两个好友
        rightNow1.set(Calendar.DAY_OF_MONTH,rightNow1.get(Calendar.DAY_OF_MONTH)-2);

        String weixinId = null;
        for(Map.Entry<String,Integer> en:infoIds){

            FriendExample friendExample = new FriendExample();
            FriendExample.Criteria criteria = friendExample.createCriteria();
            criteria.andUpdatetimeGreaterThan(rightNow1.getTime());
            criteria.andUserweixinidEqualTo(en.getKey());

            List<Friend> friendList = friendService.selectByExample(friendExample);
            if(friendList==null || friendList.size()<2)
                continue;

            int a = new Random().nextInt(friendList.size());
            int b = new Random().nextInt(friendList.size());
            while(a==b){
                b = new Random().nextInt(friendList.size());
            }
            initMembers.add(friendList.get(a).getFriendweixinid());
            initMembers.add(friendList.get(b).getFriendweixinid());
            weixinId = en.getKey();
            break;

        }
        return weixinId;
    }
    //创建艺术圈
    @RequestMapping("createcircle")
    @ResponseBody
    public Object createcircle(String circleName) throws IOException {
        Result res = new Result();
        List<String> initMembers = new ArrayList<>();
        if(circleName == null){
            res.setCode(Short.valueOf("1"));
            res.setMsg("circleName is empty!");
            return res;
        }
        CircleExample circleExample = new CircleExample();
        CircleExample.Criteria criteria = circleExample.createCriteria();
        criteria.andCirclenameEqualTo(circleName);

        List<Circle>  circles = circleService.selectByExample(circleExample);
        if(circles!=null && circles.size()>0){
            res.setCode(Short.valueOf("1"));
            res.setMsg("circle name is exsit");
            return res;
        }
        String adminWeixinId = choice(initMembers);
        if(adminWeixinId ==null || initMembers.size()<2){
            res.setCode(Short.valueOf("1"));
            res.setMsg("No enough friends to construct weixin group!");
            return res;
        }
        Circle circle = new Circle();
        circle.setCirclename(circleName);
        circle.setCreatedate(new Date());
        int r = circleService.insert(circle);

        if(r==1){
            Map<String,Integer> m = new HashMap<>();
            m.put("circleId",circle.getCircleid());
            res.setObj(m);
            Jedis jedis = null;

            String rkey = new String("cmdcmd");
            rkey+=adminWeixinId;
            CommonHeader ch = new CommonHeader();
            ch.setCmd("creategroup");
            ch.setCode(0);
            GroupInitCmd groupInitCmd = new GroupInitCmd();

            groupInitCmd.setCallbackId(circle.getCircleid());
            List<GroupInit> initList = new ArrayList<>();
            for(String gg: initMembers){
                GroupInit gi = new GroupInit();
                gi.setId(gg);
                initList.add(gi);
            }
            groupInitCmd.setList(initList);
            ch.setInfo(groupInitCmd);
            Date now = new Date();
            String name = new String();
            name = circleName+now.getTime();
            groupInitCmd.setName(name);

            String value = JSON.toJSONString(ch);
            try {
                jedis = redisSource.getConnection();
                long rr = jedis.rpush(rkey.getBytes(),SerializeUtil.serialize(value));
            }catch (Exception e){
                e.printStackTrace();
                redisSource.destoryConnection(jedis);
                res.setCode(Short.valueOf("1"));
                res.setMsg("rpush to redis failure");
                circleService.deleteByPrimaryKey(circle.getCircleid());

            } finally {
                redisSource.closeConnection(jedis);
            }
        }else{
            res.setCode(Short.valueOf("1"));
            res.setMsg("insert circle failure!");
        }
        return res;
    }
    //获取艺术圈列表
    @RequestMapping("sendmsg")
    @ResponseBody
    public Object sendmsg(String msg,String groupId) throws IOException {
        Result res = new Result();
        Jedis jedis = null;
        if(msg == null ||msg.length()<1){
            res.setCode(Short.valueOf("1"));
            res.setMsg("message content is empty");
            return res;
        }
        String rkey = new String("cmdcmd");
        Groups groups = groupService.selectByPrimaryKey(groupId);
        if(groups==null||groups.getAdminweixinid()==null){
            res.setCode(Short.valueOf("1"));
            res.setMsg("group id is invalid");
            return res;
        }
        CommonHeader ch = new CommonHeader();
        ch.setCmd("sendmsg");
        ch.setCode(0);
        MsgCmd msgCmd = new MsgCmd();
        msgCmd.setMsg(msg);
        List<MsgParam> paramList = new ArrayList<>();
        MsgParam msgParam = new MsgParam();
        msgParam.setId(groupId);
        paramList.add(msgParam);
        msgCmd.setList(paramList);
        ch.setInfo(msgCmd);

        String value = JSON.toJSONString(ch);
        String fkey = rkey+groups.getAdminweixinid();
        try {
            jedis = redisSource.getConnection();
            long rr = jedis.rpush(fkey.getBytes(),SerializeUtil.serialize(value));
        }catch (Exception e){
            e.printStackTrace();
            redisSource.destoryConnection(jedis);
            res.setCode(Short.valueOf("1"));
            res.setMsg("rpush to redis failure");


        } finally {
            redisSource.closeConnection(jedis);
        }
        return res;
    }

    //获取艺术圈列表
    @RequestMapping("circlelist")
    @ResponseBody
    public Object circlelist(Circles circles) throws IOException {
        Result res = new Result();
        if(circles== null) {
            res.setCode(Short.valueOf("1"));
            res.setMsg("circle list is invalid");
            return res;
        }
        //
        GroupsExample groupExample = new GroupsExample();
        GroupsExample.Criteria criteriaGroup = groupExample.createCriteria();

        criteriaGroup.andCircleidIn(circles.getCircleList());
        List<Groups> groups = groupService.selectByExampleWithBLOBs(groupExample);


        Date now = new Date();

        Calendar rightNow1 = Calendar.getInstance();
        rightNow1.setTime(now);
        rightNow1.set(Calendar.DAY_OF_MONTH,rightNow1.get(Calendar.DAY_OF_MONTH)-2);
        Date  accessTime = rightNow1.getTime();

        HashMap<Integer,Integer> mapCircleHistoryUserCount = new HashMap<>();
        HashMap<Integer,Integer> mapCircleUserCount = new HashMap<>();
        HashMap<Integer,Integer> mapCircleUserMinCount = new HashMap<>();
        HashMap<Integer,String>  mapCircleUserMinGroup = new HashMap<>();
        HashMap<String,byte[]>   mapGroup2QRcode = new HashMap<>();
        HashMap<Integer,String>  mapCircleUserDefaultGroup = new HashMap<>();

        for(Groups group :groups) {
            mapGroup2QRcode.put(group.getWeixingroupid(),group.getErcode());
            mapCircleUserDefaultGroup.put(group.getCircleid(),group.getWeixingroupid());
            MemberExample memberExample1 = new MemberExample();
            MemberExample.Criteria criteriaMember1 = memberExample1.createCriteria();
            criteriaMember1.andWeixingroupidEqualTo(group.getWeixingroupid());
            int cc = memberService.countByExample(memberExample1);

            if(cc <1)
                continue;
            Integer  userCount1 = mapCircleHistoryUserCount.get(group.getCircleid());
            if(userCount1 == null){
                userCount1 = new Integer(0);
            }
            userCount1 += cc;
            mapCircleHistoryUserCount.put(group.getCircleid(),userCount1);//累加记录艺术圈历史用户数


            MemberExample memberExample = new MemberExample();
            MemberExample.Criteria criteriaMember = memberExample.createCriteria();
            criteriaMember.andUpdatetimeGreaterThan(accessTime);
            criteriaMember.andWeixingroupidEqualTo(group.getWeixingroupid());
            cc = memberService.countByExample(memberExample);
            if(cc <1)
                continue;
            Integer  userCount = mapCircleUserCount.get(group.getCircleid());
            if(userCount == null){
                userCount = new Integer(0);
            }
            userCount += cc;
            mapCircleUserCount.put(group.getCircleid(),userCount);//累加记录艺术圈用户数


            //记录艺术圈中用户数最少的群
            String weixinGroupId = mapCircleUserMinGroup.get(group.getCircleid());
            Integer memberCount = mapCircleUserMinCount.get(group.getCircleid());
            if(weixinGroupId == null){
                mapCircleUserMinGroup.put(group.getCircleid(),group.getWeixingroupid());
                mapCircleUserMinCount.put(group.getCircleid(),cc);
            }else{
                if(cc < memberCount){
                    mapCircleUserMinGroup.put(group.getCircleid(),group.getWeixingroupid());
                    mapCircleUserMinCount.put(group.getCircleid(),cc);
                }
            }


        }

        List<CircleInfo> circleInfos = new ArrayList<>();

        for(Integer circleId: circles.getCircleList()){
            CircleInfo ci = new CircleInfo();
            ci.setCircleId(circleId);
            Integer nn = mapCircleHistoryUserCount.get(circleId);
            if(nn==null){
                nn = new Integer(0);
            }
            ci.setCircleHistoryUserNum(nn);
            nn = mapCircleUserCount.get(circleId);
            if(nn==null){
                nn = new Integer(0);
            }
            ci.setCircleUserNum(nn);

            String groupid = mapCircleUserMinGroup.get(circleId);
            if(groupid == null || mapGroup2QRcode.get(groupid)==null){
                groupid = mapCircleUserDefaultGroup.get(circleId);
                if(groupid==null || mapGroup2QRcode.get(groupid)==null) {
                    ci.setQrcodeBase64(null);
                }else{
                    String qrcode = new String(mapGroup2QRcode.get(groupid),"UTF-8");
                    ci.setQrcodeBase64(qrcode);
                }
            }else{
                String qrcode = new String(mapGroup2QRcode.get(groupid),"UTF-8");
                ci.setQrcodeBase64(qrcode);
            }
            circleInfos.add(ci);
        }

        CircleInfos circleInfos1 = new CircleInfos();
        circleInfos1.setCircleInfoList(circleInfos);
        res.setObj(circleInfos1);
        return  res;
    }


    //获取微信号所在的艺术圈列表
    @RequestMapping("incirclelist")
    @ResponseBody
    public Object incirclelist(String weixinId) throws IOException {
        Result res = new Result();
        if(weixinId == null) {
            res.setCode(Short.valueOf("1"));
            res.setMsg("weixinId is invalid");
            return res;
        }
        MemberExample memberExample = new MemberExample();
        MemberExample.Criteria criteriaMember = memberExample.createCriteria();
        Date now = new Date();

        Calendar rightNow1 = Calendar.getInstance();
        rightNow1.setTime(now);
        rightNow1.set(Calendar.DAY_OF_MONTH,rightNow1.get(Calendar.DAY_OF_MONTH)-3);
        Date  accessTime = rightNow1.getTime();
        criteriaMember.andUserweixinidEqualTo(weixinId);
        criteriaMember.andUpdatetimeGreaterThan(accessTime);


        List<Member> members = memberService.selectByExample(memberExample);

        List<String> groupIds = new ArrayList<>();
        for(Member m: members){
            groupIds.add(m.getWeixingroupid());
        }

        GroupsExample groupExample = new GroupsExample();
        GroupsExample.Criteria criteriaGroup = groupExample.createCriteria();
        criteriaGroup.andWeixingroupidIn(groupIds);

        List<Groups> groups = groupService.selectByExample(groupExample);
        List<Integer> circleIds = new ArrayList<>();
        for(Groups group: groups){
            circleIds.add(group.getCircleid());
        }
        Circles circles = new Circles();
        circles.setCircleList(circleIds);
        res.setObj(circles);
        return res;
    }
    //
    //刷新艺术圈，新创建艺术圈的情况下，用于快速获取艺术圈信息；

    @RequestMapping("grouprefresh")
    @ResponseBody
    public Object grouprefresh() throws IOException {
        Result res = new Result();


        Date now = new Date();
        Calendar rightNow1 = Calendar.getInstance();
        rightNow1.setTime(now);
        rightNow1.set(Calendar.MINUTE,rightNow1.get(Calendar.MINUTE)-4);
        Date  accessTime = rightNow1.getTime();
        VolunteerExample volunteerExample = new VolunteerExample();
        VolunteerExample.Criteria criteriaV = volunteerExample.createCriteria();
        criteriaV.andUpdatetimeGreaterThan(accessTime);

        List<Volunteer> volunteers = volunteerService.selectByExample(volunteerExample);

        Jedis jedis = null;
        String rkey = new String("cmdcmd");

        String value = null;
        try {
            jedis = redisSource.getConnection();
            for(Volunteer v:volunteers) {
                CommonHeader ch = new CommonHeader();
                ch.setCmd("sync");
                ch.setCode(0);
                SyncCmd syncCmd = new SyncCmd();
                List<SyncParam> syncParamList = new ArrayList<>();

                syncCmd.setList(syncParamList);
                ch.setInfo(syncCmd);
                value = JSON.toJSONString(ch);
                String fkey = rkey+v.getVolunteerweixinid();
                jedis.rpush(fkey.getBytes(),SerializeUtil.serialize(value));
            }
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(Short.valueOf("1"));
            redisSource.destoryConnection(jedis);
        } finally {
            redisSource.closeConnection(jedis);
        }
        return res;
    }
    //
    //刷新艺术圈，新创建艺术圈的情况下，用于快速获取艺术圈信息；
    // 在有些情况下，艺术圈的信息失效，需要重新获取APP端的信息，也可以调用此接口
    @RequestMapping("circlerefresh")
    @ResponseBody
    public Object circlerefresh(Integer circleId) throws IOException {
        Result res = new Result();

        if(circleId == null){
            res.setCode(Short.valueOf("1"));
            res.setMsg("circleId is invalid");
            return res;
        }
        GroupsExample groupExample = new GroupsExample();
        GroupsExample.Criteria criteriaGroup = groupExample.createCriteria();
        criteriaGroup.andCircleidEqualTo(circleId);
        Date now = new Date();

        Calendar rightNow1 = Calendar.getInstance();
        rightNow1.setTime(now);
        rightNow1.set(Calendar.DAY_OF_MONTH,rightNow1.get(Calendar.DAY_OF_MONTH)-2);
        Date  accessTime = rightNow1.getTime();
        criteriaGroup.andUpdatetimeGreaterThan(accessTime);
        List<Groups> groups = groupService.selectByExample(groupExample);

        if(groups==null ||groups.size()==0){
            res.setCode(Short.valueOf("1"));
            res.setMsg("Please try 2 minutes later.circle is not construct completely. ");
            return res;
        }
        HashMap<String,List<String>> stringListHashMap = new HashMap<>();
        for (Groups group:groups){
            List<String> stringList = stringListHashMap.get(group.getAdminweixinid());
            if(stringList == null){
                stringList = new ArrayList<>();
                stringListHashMap.put(group.getAdminweixinid(),stringList);
            }
            stringList.add(group.getWeixingroupid());
        }

        Jedis jedis = null;
        String rkey = new String("cmdcmd");

        String value = null;
        try {
            jedis = redisSource.getConnection();
           for(Map.Entry<String,List<String>> listEntry:stringListHashMap.entrySet()) {
               if(listEntry.getKey() == null || listEntry.getKey().length()==0){
                   res.setCode(Short.valueOf("1"));
                   res.setMsg("Please try 3 minutes later.circle is not construct completely. ");
                   return res;
               }
               CommonHeader ch = new CommonHeader();
               ch.setCmd("sync");
               ch.setCode(0);
               SyncCmd syncCmd = new SyncCmd();
                List<SyncParam> syncParamList = new ArrayList<>();
                for(String ss: listEntry.getValue()){
                    SyncParam  sp = new SyncParam();
                    sp.setId(ss);
                    syncParamList.add(sp);
                }
               syncCmd.setList(syncParamList);
               ch.setInfo(syncCmd);
               value = JSON.toJSONString(ch);
               String fKey = rkey+listEntry.getKey();

               jedis.rpush(fKey.getBytes(), SerializeUtil.serialize(value));
           }
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(Short.valueOf("1"));
            redisSource.destoryConnection(jedis);
        } finally {
            redisSource.closeConnection(jedis);
        }
        return res;
    }

    private boolean checkQRCodeExpire(String retMsg){
        Date now= new Date();

        GroupsExample groupsExample = new GroupsExample();
        GroupsExample.Criteria criteriaGroups = groupsExample.createCriteria();

        criteriaGroups.andErcodeinvalidtimeLessThan(now);

        criteriaGroups.andErcodeinvalidtimeIsNotNull();

        criteriaGroups.andAdminweixinidIsNotNull();

        List<Groups> groupsList = groupService.selectByExample(groupsExample);
        if(groupsList == null||groupsList.size()==0){
            return true;
        }
        Jedis jedis = null;
        String rkey = new String("cmdcmd");
        try {
            jedis = redisSource.getConnection();
            HashMap<String,List<SyncParam>> stringListHashMap = new HashMap<>();
            for(Groups groups: groupsList){
                List<SyncParam> ggList = stringListHashMap.get(groups.getAdminweixinid());
                if(ggList == null){
                    ggList = new ArrayList<>();
                    stringListHashMap.put(groups.getAdminweixinid(),ggList);
                }
                SyncParam sp = new SyncParam();
                sp.setId(groups.getWeixingroupid());
                ggList.add(sp);
            }
            for(Map.Entry<String,List<SyncParam >> gn: stringListHashMap.entrySet()){
                CommonHeader ch = new CommonHeader();
                ch.setCmd("sync");
                ch.setCode(0);
                SyncCmd syncCmd = new SyncCmd();

                syncCmd.setList(gn.getValue());
                ch.setInfo(syncCmd);
                String value = JSON.toJSONString(ch);
                String fkey = rkey+gn.getKey();
                long rr = jedis.rpush(fkey.getBytes(),SerializeUtil.serialize(value));
            }
        }catch (Exception e){
            e.printStackTrace();
            redisSource.destoryConnection(jedis);
            retMsg+="Redis server is not running yet\n";
            return false;
        } finally {
            redisSource.closeConnection(jedis);
        }
        return true;
    }

    //艺术圈自动扩展,当检测到某个艺术的微信群成员数差5个就达到上限时，
    // 自动新建一个微信群，分配给这个艺术圈。调用时机：每两个小时运行一次
    @RequestMapping("circlegrowth")
    @ResponseBody
    public Object circlegrowth() throws IOException {
        Result res = new Result();
        String  retMsg = new String();
        if(false == checkQRCodeExpire(retMsg)){
            res.setCode(Short.valueOf("1"));
            res.setMsg(retMsg);
            return res;
        }
        //检测已经启动微信的用户所管理的群
        VolunteerExample volunteerExample = new VolunteerExample();
        VolunteerExample.Criteria  criteriaV = volunteerExample.createCriteria();

        Date now = new Date();

        Calendar rightNow1 = Calendar.getInstance();
        rightNow1.setTime(now);
        rightNow1.set(Calendar.MINUTE,rightNow1.get(Calendar.MINUTE)-4);
            //聊天记录定时上传时，更新时间戳，超过4分钟没有更新，认为手机已经关闭微信了
        Date  accessTime = rightNow1.getTime();
        criteriaV.andUpdatetimeGreaterThan(accessTime);

        List<Volunteer>  volunteers =  volunteerService.selectByExample(volunteerExample);

        List<String> stringList = new ArrayList<>();
        for(Volunteer v: volunteers){
            stringList.add(v.getVolunteerweixinid());
        }
        GroupsExample groupExample = new GroupsExample();
        GroupsExample.Criteria criteriaGroup = groupExample.createCriteria();

        criteriaGroup.andAdminweixinidIn(stringList);
        List<Groups> groups = groupService.selectByExample(groupExample);

        //计算艺术圈用户最少的群 是否已经到达上限

        HashMap<Integer,String> stringStringLessGroupMap = new HashMap<>();
        HashMap<Integer,Integer> integerGroupMemberNumMap = new HashMap<>();
        HashMap<Integer,String>  integerStringAdminWeixinMap = new HashMap<>();
        rightNow1.set(Calendar.DAY_OF_MONTH,rightNow1.get(Calendar.DAY_OF_MONTH)-2);

        for(Groups group:groups){
            MemberExample memberExample = new MemberExample();
            MemberExample.Criteria criteria = memberExample.createCriteria();

            criteria.andUpdatetimeGreaterThan(rightNow1.getTime());

            int cc = memberService.countByExample(memberExample);

            if(cc<1)
                continue;

            Integer aa = integerGroupMemberNumMap.get(group.getCircleid());
            if(aa == null){
                aa = new Integer(cc);
                integerGroupMemberNumMap.put(group.getCircleid(),aa);
                stringStringLessGroupMap.put(group.getCircleid(),group.getWeixingroupid());
                integerStringAdminWeixinMap.put(group.getCircleid(),group.getAdminweixinid());
            }else{
                if(aa>cc){
                    integerGroupMemberNumMap.put(group.getCircleid(),cc);
                    stringStringLessGroupMap.put(group.getCircleid(),group.getWeixingroupid());
                    integerStringAdminWeixinMap.put(group.getCircleid(),group.getAdminweixinid());
                }
            }
        }

        CircleExample circleExample = new CircleExample();
        List<Circle> circles = circleService.selectByExample(circleExample);
        HashMap<Integer,String> circleNameMap = new HashMap<>();
        for(Circle c: circles){
            circleNameMap.put(c.getCircleid(),c.getCirclename());
        }
        Jedis jedis = null;
        String rkey = new String("cmdcmd");
        String value = null;
        try {
            jedis = redisSource.getConnection();
            for(Map.Entry<Integer,Integer> cn:integerGroupMemberNumMap.entrySet()){
                if(cn.getValue()>75){
                    List<String> initMembers = new ArrayList<>();
                    String adminWeixinId = choice(initMembers);
                    if(adminWeixinId ==null || initMembers.size()<2){
                        retMsg+="No enogh friends to create group for circle "+cn.getKey()+"\n";
                        continue;
                    }
                    List<GroupInit> initList = new ArrayList<>();
                    for(String ss: initMembers){
                        GroupInit gi = new GroupInit();
                        gi.setId(ss);
                        initList.add(gi);
                    }
                    CommonHeader ch = new CommonHeader();
                    ch.setCmd("creategroup");
                    ch.setCode(0);
                    GroupInitCmd groupInitCmd = new GroupInitCmd();

                    groupInitCmd.setCallbackId(cn.getKey());
                    groupInitCmd.setList(initList);

                    ch.setInfo(groupInitCmd);
                    String name = new String();
                    name = circleNameMap.get(cn.getKey())+now.getTime();
                    groupInitCmd.setName(name);

                    value = JSON.toJSONString(ch);
                    adminWeixinId = integerStringAdminWeixinMap.get(cn.getKey());
                    String fkey = rkey+adminWeixinId;
                    long rr = jedis.rpush(fkey.getBytes(),SerializeUtil.serialize(value));
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            res.setCode(Short.valueOf("1"));
            retMsg+="Redis server is not running\n";
            redisSource.destoryConnection(jedis);
        } finally {
            redisSource.closeConnection(jedis);
        }

        res.setMsg(retMsg);
        return res;
    }
}
